package com.yeebo.admin.service;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.yeebo.admin.domain.SysUserDomain;
import com.yeebo.constants.Constants;
import com.yeebo.domain.user.UserTokenDomain;
import com.yeebo.enums.ResultCode;
import com.yeebo.enums.user.UserPlatformEnums;
import com.yeebo.exception.ServiceException;
import com.yeebo.model.admin.SysResource;
import com.yeebo.model.admin.SysUser;
import com.yeebo.model.admin.SysUserRole;
import com.yeebo.model.user.UserToken;
import com.yeebo.rpc.admin.SysUserService;
import com.yeebo.utils.MD5Utils;
import com.yeebo.vo.admin.SysUserLoginVO;
import com.yeebo.vo.admin.SysUserManageVO;
import com.yeebo.vo.admin.SysUserRolesVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

/**
 * 系统用户服务实现类
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    private static Logger logger = LoggerFactory.getLogger(SysUserServiceImpl.class);
    @Resource
    private SysUserDomain sysUserDomain;
    @Resource
    private UserTokenDomain userTokenDomain;

    @Override
    public SysUser getUserByLoginName(String loginName) {
        return sysUserDomain.getUserByLoginName(loginName);
    }

    @Override
    public SysUserLoginVO login(String loginName, String password, String ipAddress) {
        SysUser existUser = sysUserDomain.checkUserAndPassword(loginName, password);
        sysUserDomain.updateLoginInfo(existUser, ipAddress);
        UserToken userToken = userTokenDomain.getUserTokenByUserInfo(UserPlatformEnums.ADMIN.getPlatform(), existUser.getId());
        SysUserLoginVO targetVo = new SysUserLoginVO();
        BeanUtil.copyProperties(existUser, targetVo);
        targetVo.setToken(userToken.getUserToken());
        targetVo.setTokenExpireTime(userToken.getExpireTime());
        return targetVo;
    }

    @Override
    public SysUserLoginVO getUserById(Long userId) {
        SysUser sysUser = sysUserDomain.getUserById(userId);
        SysUserLoginVO targetVo = new SysUserLoginVO();
        BeanUtil.copyProperties(sysUser, targetVo);
        return targetVo;
    }

    @Override
    public void logout() {
        try {
            Subject currentUser = SecurityUtils.getSubject();
            currentUser.logout();
        } catch (Exception ex) {
            logger.error("退出登录时报错，错误信息ex={}", ex);
        }
    }

    @Override
    public List<SysResource> loadResourcesByLoginName(String loginName) {
        SysUser sysUser = sysUserDomain.getUserByLoginName(loginName);
        List<SysResource> sysResources = sysUserDomain.loadResourcesByUserId(sysUser.getId());
        return sysResources;
    }

    @Override
    public Page<SysUserManageVO> loadSysUserManageList(Integer pageNo, Integer pageSize, String filterUsername) {
        return sysUserDomain.loadSysUserList(pageNo, pageSize, filterUsername);
    }

    @Override
    public SysUserManageVO getSysUserInfoById(Long userId) {
        return sysUserDomain.getSysUserInfoById(userId);
    }

    @Override
    public void addSysUser(String loginName, String username, String phone) {
        // 校验登录名是否重复
        SysUser checkExistUser = sysUserDomain.getUserByLoginName(loginName);
        if (checkExistUser != null) {
            throw new ServiceException(ResultCode.SYS_USER_ACCOUNT_REPEAT);
        }
        // 添加用户信息
        sysUserDomain.addSysUser(loginName, username, phone);
    }

    @Override
    public void updateSysUser(Long userId, String username, String phone, Integer status) {
        SysUser existUser = sysUserDomain.getUserById(userId);
        existUser.setUsername(username);
        existUser.setPhone(phone);
        existUser.setStatus(status);
        sysUserDomain.updateSysUser(existUser);
    }

    @Override
    public void resetSysUserPassword(Long userId) {
        SysUser existUser = sysUserDomain.getUserById(userId);
        existUser.setPassword(MD5Utils.MD5(Constants.SYS_USER_DEFAULT_PASSWORD));
        sysUserDomain.updateSysUser(existUser);
    }

    @Override
    public void deleteSysUser(Long userId) {
        SysUser existUser = sysUserDomain.getUserById(userId);
        if (existUser.getLoginName().equalsIgnoreCase("admin")
            || existUser.getLoginName().equalsIgnoreCase("super")) {
            throw new ServiceException(ResultCode.CAN_NOT_DELETE_ADMIN);
        }
        existUser.setValid(false);
        sysUserDomain.updateSysUser(existUser);
    }

    @Override
    public List<SysUserRolesVO> loadSysRoleListByUserId(Long userId) {
        return sysUserDomain.loadSysRoleListByUserId(userId);
    }

    @Override
    public void assignRolesToUser(Long userId, List<Long> roleIds) {
        List<SysUserRole> sysUserRoles = new LinkedList<>();
        for (Long roleId : roleIds) {
            SysUserRole entity = new SysUserRole();
            entity.setUserId(userId);
            entity.setRoleId(roleId);
            sysUserRoles.add(entity);
        }
        sysUserDomain.assignRolesToUser(userId, sysUserRoles);
    }

}
